/*
 * Copyright 2012 jsm.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.abiwebz.office.rm.database.configuration;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import net.abiwebz.office.rm.database.util.IWizardStoreRead;
import org.openide.WizardDescriptor;
import org.openide.util.Exceptions;

public final class DbConfigVisualPanel1 extends JPanel implements DocumentListener, IWizardStoreRead {

    public static final String PROP_IMPORT_FILE_PATH = "import_file_path";
    public static final String PROP_IMPORT_CHECK     = "import_check";
    
    /**
     * Creates new form DbConfigVisualPanel1.
     */
    public DbConfigVisualPanel1() {
        initComponents();
        // Add listeners for components
        this.tfConfigFile.getDocument().addDocumentListener(this);
        // Initialize state of components
        this.chkUseCfgFile.setSelected(false);
        chkUseCfgFileStateChanged(null); 
    }
    
    /**
     * Return file path for the configuration file.
     * 
     * @return File path in String
     */
    public String getFilePath(){
        return this.tfConfigFile.getText();
    }
    
    /**
     * Check if user ask to import data.
     * 
     * @return True if we need to import data
     */
    public boolean needImport(){
        return chkUseCfgFile.isSelected();
    }

    /**
     * Return the displayed name for this page.
     * 
     * @return The name used for display
     */
    @Override
    public String getName() {
        return "Import configuration";
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        chkUseCfgFile = new javax.swing.JCheckBox();
        lFilePath = new javax.swing.JLabel();
        tfConfigFile = new javax.swing.JTextField();
        bBrowse = new javax.swing.JButton();

        org.openide.awt.Mnemonics.setLocalizedText(chkUseCfgFile, org.openide.util.NbBundle.getMessage(DbConfigVisualPanel1.class, "DbConfigVisualPanel1.chkUseCfgFile.text")); // NOI18N
        chkUseCfgFile.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                chkUseCfgFileStateChanged(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(lFilePath, org.openide.util.NbBundle.getMessage(DbConfigVisualPanel1.class, "DbConfigVisualPanel1.lFilePath.text")); // NOI18N

        tfConfigFile.setEditable(false);
        tfConfigFile.setText(org.openide.util.NbBundle.getMessage(DbConfigVisualPanel1.class, "DbConfigVisualPanel1.tfConfigFile.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(bBrowse, org.openide.util.NbBundle.getMessage(DbConfigVisualPanel1.class, "DbConfigVisualPanel1.bBrowse.text")); // NOI18N
        bBrowse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bBrowseActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(chkUseCfgFile)
                        .addGap(0, 234, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lFilePath)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tfConfigFile))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(bBrowse)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(chkUseCfgFile)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lFilePath)
                    .addComponent(tfConfigFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bBrowse)
                .addContainerGap(139, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Set enabled or disabled other components. All components on this 
     * page become enabled when this checkbox is checked.
     * 
     * @param evt Event called when state is changed
     */
    private void chkUseCfgFileStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_chkUseCfgFileStateChanged
        // Set other components enabled if checked
        this.tfConfigFile.setEnabled(this.chkUseCfgFile.isSelected());
        this.bBrowse.setEnabled(this.chkUseCfgFile.isSelected());
        firePropertyChange(PROP_IMPORT_CHECK, 0, 1);
    }//GEN-LAST:event_chkUseCfgFileStateChanged

    /**
     * Browse for information (INF) file. This function show a open file
     * dialog to the user and when the user select is file the path is entered
     * into the file path textbox.
     * 
     * @param evt Action event for the Browse button
     */
    private void bBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bBrowseActionPerformed
        FileFilter inf = new FileNameExtensionFilter("Informations files (*.inf)", "inf");
        File currentFile = new File(getFilePath());
        JFileChooser chooser = new JFileChooser(currentFile.getParentFile());
        chooser.addChoosableFileFilter(inf);
        if(chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION){
            tfConfigFile.setText(chooser.getSelectedFile().getPath());
        }
        
    }//GEN-LAST:event_bBrowseActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bBrowse;
    private javax.swing.JCheckBox chkUseCfgFile;
    private javax.swing.JLabel lFilePath;
    private javax.swing.JTextField tfConfigFile;
    // End of variables declaration//GEN-END:variables

    /**
     * Event generated by the DocumentListener.
     * 
     * @param e Document event fired when a text component is used
     */
    @Override
    public void insertUpdate(DocumentEvent e) {
        fire(e);
    }

    /**
     * Event generated by the DocumentListener.
     * 
     * @param e Document event fired when a text component is used
     */
    @Override
    public void removeUpdate(DocumentEvent e) {
        fire(e);
    }

    /**
     * Event generated by the DocumentListener.
     * 
     * @param e Document event fired when a text component is used
     */
    @Override
    public void changedUpdate(DocumentEvent e) {
        fire(e);
    }
    
    /**
     * Standard function used in insertUpdate, removeUpdate and 
     * changedUpdate. This way we only need to update one function.
     * 
     * @param e DocumentEvent called
     */
    private void fire(DocumentEvent e){
        if(tfConfigFile.getDocument() == e.getDocument()){
            firePropertyChange(PROP_IMPORT_FILE_PATH, 0, 1);
        }
    }

    /**
     * Read data from other pages of the wizard.
     * 
     * @param wiz WizardDescriptor containing the wizard values
     */
    @Override
    public void read(WizardDescriptor wiz) {
        //Nothing to read, always new values here!
    }

    /**
     * Store data from this page of the wizard.
     * 
     * @param wiz WizardDescriptor containing the wizard values
     */
    @Override
    public void store(WizardDescriptor wiz) {
        wiz.putProperty(PROP_IMPORT_CHECK, needImport());
        //wiz.putProperty(PROP_IMPORT_FILE_PATH, getFilePath());
        if(needImport()){
            // Read the file and add the configuration
            File fileToImport = new File(getFilePath());
            Properties p = new Properties();
            try {
                p.load(new FileInputStream(fileToImport));
                wiz.putProperty(DbConfigVisualPanel2.PROP_ONLINE_DRIVER, p.getProperty(DbConfigVisualPanel2.PROP_ONLINE_DRIVER)); // Online driver
                wiz.putProperty("online_" + DriverConfigurationPanel.PROP_JDBC_URL, p.getProperty("online_" + DriverConfigurationPanel.PROP_JDBC_URL)); // Online jdbc
                wiz.putProperty(DbConfigVisualPanel3.PROP_OFFLINE_DRIVER, p.getProperty(DbConfigVisualPanel3.PROP_OFFLINE_DRIVER));
                wiz.putProperty("offline_" + DriverConfigurationPanel.PROP_JDBC_URL, p.getProperty("offline_" + DriverConfigurationPanel.PROP_JDBC_URL));
                boolean needOffline = (p.getProperty(DbConfigVisualPanel3.PROP_OFFLINE_CHECK).equals("1")) ? true : false;
                wiz.putProperty(DbConfigVisualPanel3.PROP_OFFLINE_CHECK, needOffline);
            } catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    }
}
